package com.atguigu.spzx.manager.service.impl.order;

import com.atguigu.spzx.manager.mapper.order.OrderInfoMapper;
//import com.atguigu.spzx.manager.mapper.order.OrderMapper;
import com.atguigu.spzx.manager.mapper.order.OrderStatisticsMapper;
import com.atguigu.spzx.manager.service.order.OrderStatisticsService;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderStatistics;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderStatisticsServiceImpl implements OrderStatisticsService {
    @Resource
    OrderStatisticsMapper orderStatisticsMapper;
    @Resource
    OrderInfoMapper orderMapper;
    @Override
    public Map<String,Object> list(String begin, String end) {
        List<OrderStatistics> list = orderStatisticsMapper.findByDate(begin, end);
        //前端需要的是 时间日期集合   时间日期对应的总金额集合

        List<Date> dateList = list.stream().map(OrderStatistics::getOrderDate).collect(Collectors.toList());
        List<BigDecimal> totalAmountList = list.stream().map(OrderStatistics::getTotalAmount).collect(Collectors.toList());

        Map<String,Object> map = new HashMap<>();
        map.put("dateList" , dateList);
        map.put("totalAmountList" , totalAmountList);
        return map;
    }

    @Override
    public void generateOrderStatistics() {
        String orderDate = new DateTime().minusDays(1).toString("yyyy-MM-dd");
        //查询订单数据进行统计
        List<OrderInfo> orders = orderMapper.findOrdersByOrderDate(orderDate);

        if(!CollectionUtils.isEmpty(orders)){
            //生成统计数据保存
            OrderStatistics orderStatistics = new OrderStatistics();
            //昨天的日期
            orderStatistics.setOrderDate(new DateTime().minusDays(1).toDate());
            orderStatistics.setTotalNum(new BigDecimal(orders.size()));
            orderStatistics.setTotalAmount(
                    orders.stream() //集合转为stream流
                    .map(OrderInfo::getTotalAmount) // 获取每个OrderInfo对象的totalAmount属性值返回
                            //reduce执行时 前面得到的是 totalAmount(类型为bigDecimal)的集合
                    .reduce((a,b)->a.add(b)) //对上一步返回的totalAmount集合 每两个元素进行计算处理
                    .get() //获取前面处理后的结果
                    );
            orderStatisticsMapper.save(orderStatistics);
        }

    }
}
